package com.android.ailaoshan.describtion;

import android.os.Environment;
import android.os.Message;

import com.android.ailaoshan.describtion.model.TextInfo;
import com.android.ailaoshan.task.text.TextFragment;
import com.android.ailaoshan.tools.ManagerRecorder;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

public class TextOperate {

    private TextFragment.MyHandler myHandler;

    private final String TXT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator +"AiLaoShan"+ File.separator + "Text" +File.separator;

    public TextOperate(TextFragment.MyHandler handler) {
        this.myHandler = handler;
    }

    /**
     * 保存文本文件
     */
    public void saveText(String txt,String fileName){
        new Thread(
           () ->{
               // 文件夹是否存在，不存在则创建
               File folder = new File(TXT_PATH);
               boolean mkdirSuccess = true;
               if(!folder.exists()){
                   mkdirSuccess = folder.mkdirs();
               }

               if(mkdirSuccess){
                   String textPath = TXT_PATH + fileName;
                   File textFile = new File(textPath);
                   // 文本文件存在，覆盖写入
                   if(textFile.exists()){
                       try{
                           FileOutputStream outputStream = new FileOutputStream(textFile);
                           outputStream.write(txt.getBytes("gbk"));
                           outputStream.close();

                           // 存本地成功，开始存数据库
                           saveToDB(fileName);

                           // 回调显示保存按钮
                           sendSuccess();
                       }catch (Exception e){
                           e.printStackTrace();
                           sendError();
                       }
                   }
                   // 文本文件不存在，创建文件再写入
                   else{
                       try{
                           boolean mkTextFileSuccess = textFile.createNewFile();
                           if(mkTextFileSuccess){
                               FileWriter fileWriter = new FileWriter(textFile);
                               BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                               bufferedWriter.write(txt);
                               bufferedWriter.flush();
                               bufferedWriter.close();
                               fileWriter.close();

                               // 存本地成功，开始存数据库
                               saveToDB(fileName);

                               // 回调显示保存按钮
                               sendSuccess();
                           }else{
                               sendError();
                           }
                       }catch (IOException e){
                           e.printStackTrace();
                           sendError();
                           // 可能创建了一个空文件，尝试删除文件
                           try {
                               textFile.delete();
                           }catch (Exception e1){
                               e1.printStackTrace();
                           }
                       }
                   }
               }else{
                   sendError();
               }
           }
        ).start();
    }


    /**
     * 文件名存数据库
     */
    private void saveToDB(String name){
        new Thread(
           () -> {
               // 查询未完成的记录ID
               ManagerRecorder managerRecorder = new ManagerRecorder();

               TextInfo textInfo = new TextInfo();
               textInfo.setrName(name);
               textInfo.setrId(managerRecorder.getUnfinishedId());
               textInfo.setrTime(System.currentTimeMillis());

               // 获取经纬度

               textInfo.save();
           }
        ).start();
    }

    /**
     * 存储成功回调
     */
    private void sendSuccess(){
        if(this.myHandler != null){
            Message msg = myHandler.obtainMessage();
            msg.what = 310;
            myHandler.sendMessage(msg);
        }
    }


    /**
     * 存储失败回调
     */
    private void sendError(){
        // 回调显示保存按钮
        if(this.myHandler != null){
            Message msg = myHandler.obtainMessage();
            msg.what = 311;
            myHandler.sendMessage(msg);
        }
    }
}
